package com.ailink.basic.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by Administrator on 2018/10/15
 */
public class CountDownLatchTest {

//    public static int clientTotal = 5000;
//
//    public static int threadTotal = 200;

    public static int clientTotal = 50;

    public static int threadTotal = 5;

    public static int count = 0;

    private static void add() {
        try {
            Thread.sleep(100000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count++;
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
//                try {
//                    semaphore.acquire();
//                    add();
//                    semaphore.release();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                    System.out.println("InterruptedException:" + e.toString());
//                }
                try {
                    Thread.sleep(10 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }

        for (int i = 0; i < 9; i++) {
            new Thread(() -> {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("count:" + count);
    }
}
